/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import DragTable from '@/components/DragTable';
import { message, Space, Popconfirm } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { ConnectState } from '@/models/connect';
import {
  getRefundApplyList,
  refund,
  refundMoneyAndStatus,
  refundAvailMoney,
} from '@/services/tools/refundApply';
import { options } from '@/components/_pages/tools/orderRefundApply/index.config';
import { useSelector } from 'umi';
import isArray from 'lodash/isArray';
import styles from './index.less';
import moment from 'moment';

const Index: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const handleRequest = async (params: any) => {
    const { current: page, pageSize: limit, shipper_mobile: mobile, status, order_id } = params;
    return getRefundApplyList({ page, limit, mobile, status, order_id }).then(({ data, msg }) => {
      const { list, count } = data;
      if (isArray(data.list) && data.list.length > 0) {
        return {
          data: list,
          total: count,
        };
      } else {
        message.error(msg);
        return {};
      }
    });
  };
  const delayedReload = () => {
    setTimeout(() => {
      actionRef?.current?.reload();
    }, 400);
  };
  const handleRefund = async ({ order_id }: { order_id: string }) => {
    const { code, msg } = await refund({ order_id });
    if (code == 0) {
      message.success(msg);
    } else {
      message.error(msg);
    }
    delayedReload();
  };
  const handleRefundMoneyAndStatus = async ({
    order_id,
    pay_time,
  }: {
    order_id: string;
    pay_time: string;
  }) => {
    const { code, msg } = await refundMoneyAndStatus({ order_id });
    const time = moment(pay_time).format('YYYY-MM-DD');
    if (
      !moment(time).isBetween(
        moment().subtract(1, 'month').format('YYYY-MM-DD'),
        moment().format('YYYY-MM-DD'),
        null,
        '[]',
      )
    ) {
      message.error('时间超过1个月，请提钉钉退款；');
      return;
    }
    if (code == 0) {
      message.success(msg);
    } else {
      message.error(msg);
    }
    delayedReload();
  };
  const handleRefundAvailMoney = async ({
    order_id,
    pay_time,
  }: {
    order_id: string;
    pay_time: string;
  }) => {
    const { code, msg } = await refundAvailMoney({ order_id });
    const time = moment(pay_time).format('YYYY-MM-DD');
    if (
      !moment(time).isBetween(
        moment().subtract(1, 'month').format('YYYY-MM-DD'),
        moment().format('YYYY-MM-DD'),
        null,
        '[]',
      )
    ) {
      message.error('时间超过1个月，请提钉钉退款；');
      return;
    }
    if (code == 0) {
      message.success(msg);
    } else {
      message.error(msg);
    }
    delayedReload();
  };

  const renderOptions = (record: any, handle_message_kf: string) => {
    return (
      <Space direction={winSize === 'xs' ? 'vertical' : 'horizontal'}>
        <Popconfirm
          title='你确定为此提现账户退款吗？'
          onConfirm={handleRefundMoneyAndStatus.bind(null, record)}
        >
          <a>提现账户退款</a>
        </Popconfirm>
        <Popconfirm
          title='你确定为此消费账户退款吗？'
          onConfirm={handleRefundAvailMoney.bind(null, record)}
        >
          <a>消费账户退款</a>
        </Popconfirm>
        {!handle_message_kf ? (
          <Popconfirm title='你确定拒绝吗？' onConfirm={handleRefund.bind(null, record)}>
            <a>拒绝</a>
          </Popconfirm>
        ) : null}
      </Space>
    );
  };

  const columns: ProColumns<any>[] = [
    {
      title: '处理状态',
      dataIndex: 'status',
      valueType: 'select',
      initialValue: '0',
      hideInTable: true,
      fieldProps: { options },
    },
    {
      title: 'ID',
      dataIndex: 'id',
      align: 'center',
      search: false,
      ellipsis: true,
      width: 80,
    },
    {
      title: '订单号',
      dataIndex: 'order_id',
      align: 'center',
      ellipsis: true,
      width: 130,
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      align: 'center',
      search: false,
      width: 80,
      render: (_, recrod) => {
        return recrod.status == '8' || recrod.status == -20 ? '已完成' : '已受理';
      },
    },
    {
      title: '订单渠道',
      dataIndex: 'channel',
      align: 'center',
      search: false,
      ellipsis: true,
      width: 80,
      render: (_, recrod) => {
        const { channel } = recrod;
        const platform = channel
          ? channel.includes('mina')
            ? '微快递'
            : channel.includes('minpost')
            ? '小邮筒'
            : '驿站'
          : '-';
        return platform;
      },
    },
    {
      title: '发件人姓名',
      dataIndex: 'shipper_name',
      align: 'center',
      search: false,
      ellipsis: true,
      width: 90,
    },
    {
      title: '手机号',
      dataIndex: 'shipper_mobile',
      align: 'center',
      ellipsis: true,
      width: 120,
    },
    {
      title: '支付金额',
      dataIndex: 'freight',
      align: 'center',
      search: false,
      ellipsis: true,
      width: 80,
    },
    {
      title: '支付状态',
      dataIndex: 'pay_status',
      align: 'center',
      search: false,
      ellipsis: true,
      width: 80,
      render: (_, recrod) => {
        return recrod.pay_status == 0 ? '未支付' : '已支付';
      },
    },
    {
      title: '处理状态',
      dataIndex: 'handle_status',
      align: 'center',
      search: false,
      ellipsis: true,
      width: 80,
      render: (_, recrod) => {
        return recrod.handle_status == 1 ? '已处理' : '未处理';
      },
    },
    {
      title: '处理进度',
      dataIndex: 'handle_message',
      align: 'center',
      search: false,
      ellipsis: true,
      width: 110,
    },
    {
      title: '退款申请时间',
      dataIndex: 'apply_time',
      align: 'center',
      search: false,
      ellipsis: true,
      width: 130,
    },
    {
      title: '操作',
      dataIndex: 'options',
      align: 'center',
      search: false,
      width: winSize === 'xs' ? 130 : 240,
      fixed: 'right',
      render: (_, record) => {
        const { status, handle_status, pay_status, order_id, handle_message } = record;
        const status_arr = ['0', '1', '2'].includes(status);
        const handle_status_arr = ['1', '3'].includes(handle_status);
        const handle_status_f_1 = handle_status != '1';
        const handle_status_t_3 = handle_status == '3';
        const handle_message_kf = handle_message && handle_message.includes('客服');
        if (status_arr) {
          if (!handle_status_arr && pay_status == 0) {
            return (
              <Popconfirm title='你确定拒绝吗？' onConfirm={handleRefund.bind(null, order_id)}>
                <a>拒绝</a>
              </Popconfirm>
            );
          } else if (handle_status_f_1 && pay_status !== 0) {
            if (handle_status_t_3) {
              return renderOptions(record, handle_message_kf);
            } else {
              return renderOptions(record, handle_message_kf);
            }
          }
          return;
        } else {
          return [];
        }
      },
    },
  ];
  return (
    <PageContainer>
      <DragTable>
        <ProTable<any>
          actionRef={actionRef}
          rowKey='id'
          request={handleRequest}
          columns={columns}
          className={styles.main}
          pagination={{
            pageSize: 30,
            showQuickJumper: false,
            showSizeChanger: false,
          }}
          scroll={{ x: 1200 }}
          options={false}
          search={{
            collapsed: false,
            collapseRender: false,
          }}
        />
      </DragTable>
    </PageContainer>
  );
};

export default Index;
